/** 登录相关模块 */
const fs = require("fs"), readline = require('readline'), wd = require('webdriver'), querystring = require('querystring'), path = require('path');
const pan = require("../pan");

let uc = "user";
/** 检测登录状态 */
function checkLogin(cb, isui = false, ucf){
	if(ucf) uc = ucf;
	fs.stat("./" + uc + ".json",(err, stats)=>{
		if(err){
			//使用命令行打印出访问地址，自己复制到浏览器登录成功后的地址再复制到命令行
			//login(cb);
			//使用webdriver弹出浏览器然后登录
			if(isui) loginBrower(cb);
			else login(cb);
			return;
		}
		let user = require("../" + uc + ".json");
		cb(user);
	})
}

function login(cb){
	console.log("用户浏览器访问下面地址：")
	console.log("https://openapi.baidu.com/oauth/2.0/authorize?response_type=token&client_id=" + pan.client_id + "&redirect_uri=oob&scope=basic,netdisk&login_type=sms");
	
	let rl = readline.createInterface({
		input: process.stdin,
		output: process.stdout
	});
	rl.question('复制登录成功后的地址：', (answer) => {
		let query = querystring.parse(answer.substr(answer.indexOf("#")+1));
		fs.writeFile("./" + uc + ".json", JSON.stringify(query), ()=>{
			delete require.cache[__dirname + path.sep + ".." + path.sep + uc + ".json"];
			cb(query);
		});
	});
}

async function loginBrower(cb){
	const { spawn } = require('child_process');
	let runwd = spawn("geckodriver.exe");
	
	const client = await wd.default.newSession({
        path: '/',
        capabilities: { browserName: 'firefox' }
    })
	await client.navigateTo("https://openapi.baidu.com/oauth/2.0/authorize?response_type=token&client_id=" + pan.client_id + "&redirect_uri=oob&scope=basic,netdisk&login_type=sms");
	let cknum = 0;
	function wt(){
		setTimeout(async ()=>{
			cknum++;
			let url = await client.getUrl();
			if(url.indexOf("login_success") != -1){
				let query = querystring.parse(url.substr(url.indexOf("#")+1));
				fs.writeFile("./" + uc + ".json", JSON.stringify(query), ()=>{
					delete require.cache[__dirname + path.sep + ".." + path.sep + uc + ".json"];
					cb(query);
				});
				await client.deleteSession();
				runwd.kill();
			}else{
				if(cknum < 5*12){
					wt();
				}else{
					await client.deleteSession();
					runwd.kill();
					cb(null);
				}				
			}
		}, 5000);
	}
	wt();
}

exports.checkLogin = checkLogin;
exports.loginBrower = loginBrower;
exports.login = login;